<template>
  <el-dialog title="订单审批" :visible.sync="visible" :center="true" width="82%" :close-on-click-modal="false">
    <el-row>
      <el-col :span="18">
        <el-descriptions class="margin-top" :column="3" :size="size" border>
          <el-descriptions-item>
            <template slot="label">
              订单编号
            </template>
            {{ toolOrderApprovalVO.sn }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              订单类别
            </template>
            {{ toolOrderApprovalVO.orderType }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">客户名称
            </template>
            {{ toolOrderApprovalVO.companyName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">订货人
            </template>
            {{ toolOrderApprovalVO.contactsName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">电话
            </template>
            {{ toolOrderApprovalVO.contactsMobile }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">职务
            </template>
            {{ toolOrderApprovalVO.contactsDuties }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">收货人
            </template>
            {{ toolOrderApprovalVO.cargoReceiver }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">电话
            </template>
            {{ toolOrderApprovalVO.cargoReceiverMobile }}
          </el-descriptions-item>
          <el-descriptions-item :span="2">
            <template slot="label">地址
            </template>
            {{ toolOrderApprovalVO.address }}
          </el-descriptions-item>
        </el-descriptions>
      </el-col>
      <el-col :span="6"
              style="display: flex; justify-content: space-between; border: 1px solid #ececec; align-items: center">
        <div style="background-color: #fafafa; width: 80px; height: 100%; color: #909399;font-weight: 100;font-size:
              12px; text-align: center; line-height: 90px">
          <span>附件</span>
        </div>
        <el-link v-for="attachment in toolOrderApprovalVO.contract" :key="attachment.id"
                 :href="attachment.filePath"
                 target="_blank">
          {{ attachment.filePath.split('/').pop() }}
        </el-link>
      </el-col>
    </el-row>


    <el-table
        :data="toolOrderApprovalVO.toolOrderItemApprovalVOS" border
        stripe
        style="width: 100%; margin-top: 20px" size="mini" :show-summary="true">
      <el-table-column label="序号" width="50" type="index"></el-table-column>
      <el-table-column label="产品名称" width="150px" prop="name"></el-table-column>
      <el-table-column label="产品图纸" width="150px" prop="toolAttachments">
        <template slot-scope="scope">
          <el-link v-for="attachment in scope.row.toolAttachmentVOS" :key="attachment.id"
                   :href="attachment.filePath"
                   target="_blank">
            {{ attachment.filePath.split('/').pop() }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="图号" width="100px" prop="drawingNumber"></el-table-column>
      <el-table-column label="数量" width="70px" prop="number"></el-table-column>
      <el-table-column label="单价" width="70px" prop="unitPrice"></el-table-column>
      <el-table-column label="总价" width="90px" prop="amountMoney"></el-table-column>
      <el-table-column label="交货时间" width="100px" prop="requestDeliveryTime"></el-table-column>
      <el-table-column label="生产方式" width="90px" prop="optionsProduction"></el-table-column>
      <el-table-column label="数量" width="70px" prop="quantity"></el-table-column>
      <el-table-column label="外协单位" prop="teamworkCompany"></el-table-column>
    </el-table>
    <el-card shadow="never" style="height: 150px; margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>审批记录</span>
      </div>
      <div ref="canvas" style="width:auto;height: auto;"></div>
    </el-card>
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>审批意见</span>
      </div>
      <el-timeline style="padding: 0 !important;">
        <el-timeline-item
            v-for="(item, index) in processCommentArray"
            :key="index"
            :timestamp=item.taskName placement="top">
          <div
              style="display: flex; align-items: center; justify-content: space-between; width: 100%;border: 1px solid #ebeef5; padding: 0 10px">
            <h4>{{ item.userId }}&nbsp;:&nbsp;{{ item.message }}</h4>
            <h4>{{ item.time }}</h4>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>
    <el-row>
      <el-col :span="24">
        <el-input type="textarea" size="mini" rows="3" placeholder="请填写处理意见"
                  v-model="gmApprovalComment"></el-input>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-button type="primary" size="mini" @click="approval">通 过</el-button>
        <el-button type="warning" size="mini" @click="cancle">退 回</el-button>
      </el-col>
    </el-row>


  </el-dialog>
</template>

<script>
import BpmnModeler from "bpmn-js/lib/Modeler";
import "bpmn-js/dist/assets/diagram-js.css";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn.css";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css";
import bpmnXML from '@/assets/toolProcess.bpmn20.xml';


export default {
  name: "GMApprovalToolOrder",
  props: {
    historyData: Object
  },
  data() {
    return {
      size: 'mini',
      toolOrderApprovalVO: {
        sn: '',
        contract: [],
        orderType: '',
        companyName: '',
        contactsName: '',
        contactsDuties: '',
        contactsMobile: '',
        cargoReceiver: '',
        cargoReceiverMobile: '',
        address: '',
        toolOrderItemApprovalVOS: [{
          id: '',
          orderId: '',
          name: '',
          toolAttachmentVOS: [],
          number: '',
          unitPrice: '',
          amountMoney: '',
          drawingNumber: '',
          requestDeliveryTime: '',
          optionsProduction: '',
          teamworkCompany: '',
          quantity: '',
        }]
      },
      taskId: '',
      fileList: [],
      gmApprovalComment: '审批意见示例',
      bpmnModeler: null,
      processCommentArray: [],
    }
  },
  computed: {
    visible: {
      get() {
        return this.$store.state.isVisible;
      },
      set(value) {
        this.$store.commit('setIsVisible', value);
      }
    },
  },
  watch: {
    visible(newVal) {
      console.log('Visible changed to: ', newVal);
    }
  },
  methods: {
    importXMLPromise(xmlData) {
      return new Promise((resolve, reject) => {
        this.bpmnModeler.importXML(xmlData, (err, warnings) => {
          if (err) {
            reject(err);
          } else {
            resolve(warnings);
          }
        });
      });
    },
    loadBPMN() {
      return this.importXMLPromise(bpmnXML).then(warnings => {
        this.bpmnModeler.get('canvas').zoom('fit-viewport');
        return warnings; // 可以返回 warnings 或其他有用的信息
      }).catch(error => {
        console.error('导入流程失败', error);
        this.$message.error('导入失败，请检查XML格式');
        throw error; // 重新抛出错误，以便可以在外部捕获
      });
    },
    applyColors() {
      const elementRegistry = this.bpmnModeler.get('elementRegistry');
      const modeling = this.bpmnModeler.get('modeling');
      // 定义颜色映射
      const colors = {
        waitingToDo: '#E6A23C',
        highPoint: '#E1F3D8',
        iDo: '#67C23A',
        highLine: '#D8E0D4'
      };
      // 遍历 historyData 并应用颜色
      Object.keys(this.historyData).forEach(key => {
        this.historyData[key].forEach(id => {
          if (id) {
            const element = elementRegistry.get(id);
            if (element) {
              // 判断元素类型，应用不同的样式
              if (element.type === 'bpmn:SequenceFlow') { // 对于连线
                modeling.setColor([element], {
                  stroke: colors[key]
                });
              } else { // 对于用户任务节点
                modeling.setColor([element], {
                  stroke: '#545454', // 边框颜色为黑色
                  fill: colors[key], // 填充颜色
                  color: colors[key] // 文本颜色
                });
              }
            }
          }
        });
      });
    },
    cancle() {
      this.$store.commit("setIsVisible", false)
    },
    approval() {
      const comment = this.gmApprovalComment
      this.$http.post(`/tool/gmApproval/${this.taskId}/${this.toolOrderApprovalVO.sn}`, {comment: comment}, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(response => {
        if (response.data.code == 1) {
          this.$message({type: 'success', showClose: true, message: '审批完成，下一步陆彦臻'})
        } else {
          this.$message({type: 'error', showClose: true, message: '审批失败，请联系管理员'})
        }
      })
      this.$store.commit("setIsVisible", false)
    }
  },
  mounted() {
    this.taskId = this.$store.state.taskId
    console.log(this.taskId)
    console.log(JSON.stringify(this.historyData, null, 2))
    this.$http.get(`/tool/showOrderApprovalVO/${this.taskId}`).then(response => {
      if (response.data.code == 1) {
        this.toolOrderApprovalVO = response.data.data
      } else {
        console.log("获取订单信息失败")
      }
    })
    this.$nextTick(() => {
      if (this.$refs.canvas) {
        console.log(this.$refs.canvas)
        this.bpmnModeler = new BpmnModeler({
          container: this.$refs.canvas,
          additionalModules: [
            {
              // 禁用滚轮滚动
              zoomScroll: ["value", ""],
              // 禁止拖动线
              bendpoints: ["value", ""],
              // 禁用左侧面板
              paletteProvider: ["value", ""],
              // 禁止点击节点出现contextPad
              contextPadProvider: ["value", ""],
              // 禁止双击节点出现label编辑框
              labelEditingProvider: ["value", ""]
            }
          ]
        });
        console.log("BpmnModeler initialized inside $nextTick:", this.bpmnModeler);
        this.loadBPMN().then(() => {
          this.applyColors()
        })
      } else {
        console.error("渲染流程图所在容器不可用 after $nextTick");
      }
    });
    this.$http.get(`/history/comment/${this.taskId}`).then((response) => {
      if (response.data.code == 1) {
        this.processCommentArray = response.data.data
      }
    })
  },

}
</script>

<style scoped>
::v-deep .el-card__header {
  padding: 5px 10px !important;
}
</style>